package cn.org.spring.wechar.controller;

import cn.org.spring.common.util.XmlUtils;
import cn.org.spring.wechar.bean.message.TextMessage;
import cn.org.spring.wechar.constant.MessageType;
import cn.org.spring.wechar.context.ContextMessageFactory;
import cn.org.spring.wechar.service.message.ImageMessageService;
import cn.org.spring.wechar.service.message.TextMessageService;
import cn.org.spring.wechar.utils.AccessAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * @auther: wanghongjie
 * @blame: wanghongjie
 * @date: 2020-10-08 17:24
 * @Description:
 */
@RestController
@RequestMapping("/v1/weChar")
public class WeCharController {


    private String token = "julywhj";

    @Autowired
    private ContextMessageFactory contextMessageFactory;

    @GetMapping
    public String getWeChar(@RequestParam String signature,
                            @RequestParam String timestamp,
                            @RequestParam String nonce,
                            @RequestParam String echostr) {
        System.out.println("signature :" + signature);
        System.out.println("timestamp :" + timestamp);
        System.out.println("nonce :" + nonce);
        System.out.println("echostr :" + echostr);
        if (AccessAuthentication.of(token, timestamp, nonce, signature).checkSignature()) {
            return echostr;
        }
        return null;
    }

    @PostMapping
    public String post(@RequestBody String message) throws Exception {
        System.out.println("接收到微信公众平台消息：" + message);
        Map<String, Object> stringObjectMap = XmlUtils.xmlStrToMap(message);
        MessageType msgType = MessageType.getType(stringObjectMap.get("MsgType").toString());
        return contextMessageFactory.doAction(msgType, stringObjectMap);
    }


    /**
     * 服务检查接口
     *
     * @return
     */
    @GetMapping("/isWorker")
    public String isWorker() {
        return "Is Worker !";
    }

}
